var express = require('express')
var router = express.Router()

// 导入db，操作数据库
const { getAll, getById, exec } = require('../db')

/**
 * 获取所有评论
 * GET /comment
 */
router.get('/', async (req, res) => {
  let sql = `SELECT * FROM bk_comment ORDER BY comment_id  DESC`
  const data = await getAll(sql)
  // 编写响应内容
  res.send({
    code: 0,
    message: '获取评论成功',
    result: data,
  })
})

/**
 * 获取某一文章下的所有评论
 * GET /comment/:id
 */

router.get('/:id', async (req, res) => {
  const { id } = req.params
  let sql = `SELECT * FROM bk_comment WHERE article_id=${id}`
  const data = await getAll(sql)
  // 编写响应内容
  res.send({
    code: 0,
    message: '获取评论成功',
    result: data,
  })
})

/**
 * 添加评论
 * POST /comment
 */
router.post('/', async (req, res) => {
  const { user_name, user_email, article_id, comment_count, comment_content } =
    req.body
  let sql = `INSERT INTO bk_comment (user_name,user_email,article_id,comment_count,comment_content) VALUES ('${user_name}','${user_email}',${article_id},${comment_count},'${comment_content}')`
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '添加评论成功',
    result: {
      comment_id: data.insertId,
      user_name,
      user_email,
      article_id,
      comment_count,
      comment_content,
    },
  })
})

/**
 * 修改评论
 * PUT /comment/:id
 */
router.put('/:id', async (req, res) => {
  const { id } = req.params
  const { comment_content } = req.body
  let sql = `UPDATE bk_comment SET comment_content='${comment_content}' WHERE comment_id=${id}`
  await exec(sql)
  res.send({
    code: 0,
    message: '修改评论成功',
    result: {
      id,
      comment_content,
    },
  })
})

/**
 * 删除评论
 * DELETE /comment/:id
 */
router.delete('/:id', async (req, res) => {
  const { id } = req.params
  let sql = `DELETE FROM bk_comment WHERE comment_id=${id}`
  await exec(sql)
  res.send({
    code: 0,
    message: '删除评论成功',
    result: '',
  })
})

module.exports = router
